package com.qf.web.servlet;

import com.alibaba.fastjson.JSON;
import com.qf.domain.Goods;
import com.qf.domain.GoodsType;
import com.qf.domain.Order;
import com.qf.domain.User;
import com.qf.sevice.GoodsService;
import com.qf.sevice.GoodsTypeService;
import com.qf.sevice.Impl.GoodsServiceImpl;
import com.qf.sevice.Impl.GoodsTypeServiceImpl;
import com.qf.sevice.Impl.OrderServiceImpl;
import com.qf.sevice.Impl.UserServiceImpl;
import com.qf.sevice.OrderService;
import com.qf.sevice.UserService;
import com.qf.utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * projectName:Shopping
 * author:RongChao
 * time:2022/4/21 9:19
 * description:
 */
@WebServlet("/adminservlet")
@MultipartConfig(maxFileSize = 1024*1024*5,maxRequestSize = 1024*1024*20)
public class AdminServlet extends BaseServlet {
        UserService userService = new UserServiceImpl();
        GoodsTypeService goodsTypeService = new GoodsTypeServiceImpl();
        GoodsService goodsService = new GoodsServiceImpl();
        OrderService orderService = new OrderServiceImpl();
    public String updateGoods(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String price = request.getParameter("price");
        String pubdate = request.getParameter("pubdate");
        String typeid = request.getParameter("typeid");
        String intro = request.getParameter("intro");
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
        goodsService.update(name,Double.parseDouble(price),pubdate,Integer.parseInt(typeid),intro,Integer.parseInt(id));
        return "forward:adminservlet?method=getGoodsList";
    }

        public String getAllOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {
            List<Order> orderList = orderService.findAllOrder();
            request.setAttribute("orderList",orderList);
            return "forward:/admin/showAllOrder.jsp";

        }
        public String addGoods(HttpServletRequest request, HttpServletResponse response) throws Exception {
            //日期格式化
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
            String name = request.getParameter("name");
            int typeid = Integer.parseInt(request.getParameter("typeid"));
            Date pubdate = sdf.parse(request.getParameter("pubdate"));
            int price = Integer.parseInt(request.getParameter("price"));
            int star = Integer.parseInt(request.getParameter("star"));
            String intro = request.getParameter("intro");
            //1.接收上传的图片
            Part picture = request.getPart("picture");
            //2.创建上传文件路径
            String basePath = this.getServletContext().getRealPath("WEB-INF/goods");
            File dir = new File(basePath);
            //2.1如果文件不存在，创建上传目录
            if(!dir.exists()){
                dir.mkdirs();
            }

            //3.处理IE浏览器路径问题
            String dis = picture.getHeader("Content-Disposition");
            String filename = dis.substring(dis.lastIndexOf("filename=")+10,dis.length()-1);
            filename = filename.substring(filename.lastIndexOf("\\")+1);

            //4.获取文件扩展名
            String substring = filename.substring(filename.lastIndexOf(".") + 1);
            //5.生成新的文件扩展名
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String newFilename = uuid+"."+substring;

            //6.完成文件上传
            //6.1判断文件名是否为空
            if(!filename.equals("")){
                //不为空下保存文件
                picture.write(basePath+File.separator+newFilename);
                //删除临时文件
                picture.delete();
            }
            //将从前端得到的数据封装到类中，穿给底层
            Goods goods = new Goods(0,name,pubdate,newFilename,price,star,intro,typeid);
            goodsService.addGoods(goods);
            List<Goods> goodsList= goodsService.findAllGoods();
            request.setAttribute("goodsList",goodsList);
            return "forward:/admin/showGoods.jsp";
        }


        public String getGoodsList(HttpServletRequest request, HttpServletResponse response) throws Exception {
            List<Goods> goodsList = goodsService.findAllGoods();
            request.setAttribute("goodsList",goodsList);
            return "forward:/admin/showGoods.jsp";
        }


        public String getGoodsType(HttpServletRequest request, HttpServletResponse response) throws Exception {
            String flag = request.getParameter("flag");
            if ("show".equals(flag)){
                //展示所有商品类型
                List<GoodsType> goodsTypeList = goodsTypeService.selectAllOrders();
                request.setAttribute("goodsTypeList",goodsTypeList);
                return "forward:/admin/showGoodsType.jsp";
            }else {
                String level = request.getParameter("goodsParent");
                String typename = request.getParameter("typename");
                List<GoodsType> goodsTypeList = goodsTypeService.selectAllOrders();
                request.setAttribute("goodsTypeList",goodsTypeList);
                goodsTypeService.addGoodsType(level,typename);
                return "forward:/admin/addGoodsType.jsp";
            }

        }

        public void searchUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String username = request.getParameter("username");
        String gender = request.getParameter("gender");
        List<User> list=userService.findUserByUsernameAndGender(username,gender);
        Object json = JSON.toJSON(list);
        response.setCharacterEncoding("UTF-8");
        response.getWriter().print(json);
    }

        public void deleteUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");
        userService.delectById(Integer.parseInt(id));
        response.getWriter().write("success");
    }

    public void getUserList(HttpServletRequest request, HttpServletResponse response) throws Exception {

        List<User> list=userService.findAlluser();
        Object json = JSON.toJSON(list);
        response.setCharacterEncoding("UTF-8");
        response.getWriter().print(json);
    }





    public String loginadminLogin(HttpServletRequest request, HttpServletResponse response) throws Exception{
       String username = request.getParameter("username");
       String password = request.getParameter("password");

       if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
           return "redirect:/admin/login.jsp";
       }
       //通过用户名查权限
       Boolean boo=userService.findByNameInRole(username);
       if (boo){
           User admin = userService.login(username, password);
           if (admin != null){
               request.getSession().setAttribute("admin",admin);
               return "redirect:/admin/admin.jsp";
           }else {
               return "redirect:/admin/login.jsp";
           }
       }else{
           return "redirect:/admin/login.jsp";
       }
   }
}
